import { WriteCmdEvent } from '../Libs/Framework/Event/WriteCmdEvent';
import { CacheManager } from '../Libs/Framework/Managers/CacheManager';
import { EventManager } from '../Libs/Framework/Managers/EventManager';
import { StoreManager } from '../Libs/Framework/Managers/StoreManager';
import { Assets } from '../Libs/Framework/Support/Assets';
import FScene from "../Libs/Framework/Support/FScene";
import { Fun } from '../Libs/Framework/Utility/dx/Fun';
import { WriteCommand } from '../Libs/NetWork/WriteCommand/WriteCommand';
import PlayerModule from '../Modules/GameCommon/PlayerModule';
import { MajongOpType, MajongsConfig, MajongsHoldsConfig } from './../Libs/Config/Config';
import { GameEvent, GameQingPu } from './../Libs/Framework/Event/GameEvent';
import { GameDataManager } from './../Libs/Framework/Managers/GameDataManager';
import { ResouceManager } from './../Libs/Framework/Managers/ResouceManager';
import { HelpTools } from './../Libs/Utils/HelpTools';
interface deskPlayerInfo {
    infoNode: PlayerModule,
    HoldsNode: cc.Node,
    FoldsNode: cc.Node,
}

const { ccclass, property } = cc._decorator;
@ccclass
export default class QpmjScene extends FScene {
    public static ClassName: string = "QpmjScene";


    private gameScene: string = "qpmj"
    private _caninitSuccess: boolean = false  //场景是否初始化完毕
    private _player: deskPlayerInfo[] = []
    private _OpenCard: cc.Node = null //出牌的node
    private _mjsData: number[] = null //保存自己的牌数据
    private _lastMoPai : number = -1   //最后摸的一张牌

    @property(cc.Node)
    private playerNode: cc.Node = null //持有玩家信息的节点
    @property(cc.Node)
    private playerHolds: cc.Node = null //持有手牌信息的节点
    @property(cc.Node)
    private playerFolds: cc.Node = null //持有打出去牌信息的节点

    public onLoad(): void {
        super.onLoad()
        // ResouceManager.LoadPrefab('GameCommon/Self_holds_Mahjongs', Fun(res => StoreManager.NewNode(CacheManager.GetCache(res)), this));



    }

    public start(): void {
        this.initView()
        this.NetWorkTest()
        //this.Debug()
    }


    //带服务器的测试
    private NetWorkTest(): void {
        GameDataManager.game.curGame = this.gameScene
        new WriteCommand(WriteCmdEvent.CMD_ReJoinDesk)
        this._lastMoPai = -1
        this.initHolds()
        this.initFolds()

    }
    //本地测试
    private Debug(): void {

        setTimeout(() => {
            GameDataManager.game.debugMode = true
            GameDataManager.game.playerId = 876980

            //测试数据
            let enterData = { "id": "qpmj", "action": "onPlayerEnter", "data": { "data": [{ "acId": 876980, "deskPos": 0, "headUrl": "www.baidu.com", "ip": "", "isExit": false, "isReady": false, "nickname": "我是账号wx", "offline": false, "score": 0, "sex": 1 }, { "acId": 123456, "deskPos": 1, "headUrl": "http://123", "ip": "", "isExit": false, "isReady": true, "nickname": "我是账号2", "offline": false, "score": 0, "sex": 1 }, { "acId": 342312, "deskPos": 2, "headUrl": "http://www.baidu.com", "ip": "", "isExit": false, "isReady": true, "nickname": "我是账号1", "offline": false, "score": 0, "sex": 4 }, { "acId": 654321, "deskPos": 3, "headUrl": "http://123", "ip": "", "isExit": false, "isReady": true, "nickname": "我是账号3", "offline": false, "score": 0, "sex": 1 }] } }
            this.showPlayerinfo(enterData.data)
            GameDataManager.room.getSelfPlayer().canPai = true
            //this.initFolds()
            this.initHolds()
            let mjs = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
            this.ShowHoldsCard(mjs)
        }, 300);
    }

    //收到服务器发来的消息
    private msgHandle(data: any): void {
        let action = data.data.action
        let gamedata = data.data.data
        switch (action) {
            case GameQingPu.onDeskBasicInfo:
                //游戏牌桌数据
                break
            case GameQingPu.onPlayerEnter:
                this.showPlayerinfo(gamedata)
                //玩家进入桌子
                break
            case GameQingPu.onDuanPai:
                this.onDuanPai(gamedata)
                break
            case GameQingPu.onMoPai:
                this.onMoPai(gamedata)
                break
            case GameQingPu.onBuHua:
                this.onBuHua(gamedata)
            break;
            case GameQingPu.onOpTypeDo: //玩家做了什么操作
                this.opTypeHandler(gamedata)
                break
            default:
                console.log("收到服务器的消息, ", data)

        }
    }

    //初始化界面，刚开始加载的时候
    private initView(): void { }

    protected addEvents(): void {
        EventManager.addEvent(this, GameEvent.ON_GAME_QPMJ_HANDLE, this.msgHandle)
    }

    // --------------------- 界面显示Start

    //断牌,服务器发送手牌过来了 处理显示
    private onDuanPai(data: any): void {
        let tempData = data.accountInfo
        let markerId = data.markerId
        for (let idx in tempData) {
            let acId = tempData[idx].acId
            this._player[acId].infoNode.setReady(false)
            if (markerId == acId) {
                let p = GameDataManager.room.getPlayerAll()
                p[markerId].canPai = true
            }
            if (acId == GameDataManager.game.playerId) {
                this.ShowHoldsCard(tempData[idx].mjs)
                //this._player[tempData[idx].acId].HoldsNode
            } else {
                for (let i = 0; i < tempData[idx].mjs.length; i++) {
                    //单独处理右边
                    if (this._player[acId].HoldsNode.name == "right") {
                        let index = tempData[idx].mjs.length - i
                        this._player[acId].HoldsNode.children[index].active = true
                    } else {
                        this._player[acId].HoldsNode.children[i].active = true
                    }
                }
            }
        }
    }

    //显示自己的牌
    private ShowHoldsCard(data: number[]): void {
        let config = MajongsHoldsConfig.Holds[0]
        data = data.sort(function (a, b) { return a - b })
        this._mjsData = data
        for (let i = 0; i < data.length; i++) {
            let sp = this._player[GameDataManager.game.playerId].HoldsNode.children[i].children[0].getComponent(cc.Sprite)
            let path = MajongsConfig.Atlas + config.cardPath + HelpTools.TileFromID(data[i])

            ResouceManager.LoadSpriteFrame(path, sp, Fun(() => {
                sp.node.parent.active = true
            }, this))
            this._player[GameDataManager.game.playerId].HoldsNode.children[i].tag = data[i]
        }
        new WriteCommand(WriteCmdEvent.CMD_QiPaiFinished)
        this.onClickCardEvent()

    }

    //根据数据显示用户界面
    private showPlayerinfo(data: any): void {
        GameDataManager.room.addPlayer(data.data)
        let p = GameDataManager.room.getPlayerAll()
        for (let player in p) {
            let local = GameDataManager.room.getLocalPost(p[player].deskPos)
            let item: deskPlayerInfo = <any>{}
            item.infoNode = this.playerNode.children[local].getComponent(PlayerModule)
            item.infoNode.clearView()
            item.HoldsNode = this.playerHolds.children[local]
            item.FoldsNode = this.playerFolds.children[local]
            this._player[player] = item

            item.infoNode.showPlayer(p[player])
        }
    }

    //创建手牌
    private initHolds(): void {
        for (let i = 0; i < MajongsHoldsConfig.Holds.length; i++) {
            let config = MajongsHoldsConfig.Holds[i]
            for (let j = 0; j < 14; j++) {
                let Mj: cc.Node = StoreManager.NewNode(CacheManager.GetCache(Assets.GetPrefab('GameCommon/Self_holds_Mahjongs')));

                let sp = Mj.getComponent(cc.Sprite)
                ResouceManager.LoadSpriteFrame(MajongsConfig.Atlas + config.resouce, sp)

                Mj.setPosition(config.pos.x + j * config.offset.x, config.pos.y + j * config.offset.y)
                if (i == 3) {
                    Mj.setLocalZOrder(14 - j)
                }

                if (j == 13) {
                    Mj.x = config.pos.x + j * config.offset.x + config.last.x
                    Mj.y = config.pos.y + j * config.offset.y + config.last.y
                }

                Mj.children[0].active = config.showCard
                Mj.active = false
                this.playerHolds.children[i].addChild(Mj)
            }
        }
    }

    //创建出牌区
    private initFolds(): void {
        for (let i = 0; i < MajongsHoldsConfig.Folds.length; i++) {
            let config = MajongsHoldsConfig.Folds[i]
            let zIndex = 30
            for (let j = 0; j < 30; j++) {
                let Mj: cc.Node = StoreManager.NewNode(CacheManager.GetCache(Assets.GetPrefab('GameCommon/Flods_Out')));
                let sp = Mj.getComponent(cc.Sprite)

                ResouceManager.LoadSpriteFrame(MajongsConfig.Atlas + config.resource, sp, Fun(() => {
                    let sp2 = Mj.children[0].getComponent(cc.Sprite)
                    ResouceManager.LoadSpriteFrame(MajongsConfig.Atlas + config.cardPath + String(j + 1), sp2, Fun(() => {
                        if (i == 3) {
                            sp2.node.x = 1,
                                sp2.node.y = 7
                            sp2.node.setScale(-1, -1)
                        }
                        // Mj.active = true
                    }, this))
                }, this))

                let pIdx = 0
                let pIdy = 0
                if (i == 0 || i == 2) {

                    pIdx = j % 10
                    pIdy = Math.floor(j / 10)
                    zIndex = i == 0 ? 30 - j : j

                    // console.log(config.pos.x  + pIdx * config.offset.x,config.pos.y + pIdy * config.offset.y,zIndex)
                } else if (i == 1 || i == 3) {
                    pIdx = Math.floor(j / 10)
                    pIdy = j % 10

                    zIndex = i == 3 ? 30 - j : j
                }
                if (i == 3) {
                    console.log("X", config.pos.x + pIdx * config.offset.x, "Y", config.pos.y + pIdy * config.offset.y)
                }
                Mj.x = config.pos.x + pIdx * config.offset.x
                Mj.y = config.pos.y + pIdy * config.offset.y
                Mj.zIndex = zIndex

                // config.pos.x + j * config.offset.x + config.last.x
                this.playerFolds.children[i].addChild(Mj)
                Mj.active = false
            }

        }
    }

    //根据自己手牌,然后重新生成位置
    private refresHoldsPos(mjs: number[]): void {
        // let mjs = []
        // mjdata.sort(function(a,b){return a - b})
        // if(this._lastMoPai != -1){
        //     mjs = mjdata.concat(this._lastMoPai)
        // }else{
        //     mjs = mjdata
        // }
       
        mjs.sort(function(a,b){return a-b})
        this._mjsData = mjs;
  

        let selfHols = this._player[GameDataManager.game.playerId].HoldsNode
        let config = MajongsHoldsConfig.Holds[0]
        let index = 0
        let start = 13 - mjs.length
        for (let i = 0; i < 14; i++) {
            if (mjs[index] != undefined && i >= start) {
                let sp = selfHols.children[i].children[0].getComponent(cc.Sprite)
                let path = MajongsConfig.Atlas + config.cardPath + HelpTools.TileFromID(mjs[index])
                ResouceManager.LoadSpriteFrame(path, sp)
                selfHols.children[i].tag = mjs[index]
                selfHols.children[i].active = true
                selfHols.children[i].setPosition(config.pos.x + i * config.offset.x, config.pos.y + i * config.offset.y)
                index++
            } else {
                selfHols.children[i].tag = -1
                selfHols.children[i].active = false
                selfHols.children[i].setPosition(config.pos.x + i * config.offset.x,
                    config.pos.y + i * config.offset.y)
            }

            if (i == 13) {
                selfHols.children[i].setPosition(config.pos.x + i * config.offset.x + config.last.x,
                    config.pos.y + i * config.offset.y + config.last.y)
            }
        }
    }

    //整理自己的手牌,携带了动作特效
    private refresHolds(mj: number): void {
        //发送出牌命令
        new WriteCommand(WriteCmdEvent.CMD_OpChoose, MajongOpType.chupai, mj)
        //拿到自己的手牌节点
        let selfHols = this._player[GameDataManager.game.playerId].HoldsNode
        this._OpenCard = null
        this._mjsData.splice(this._mjsData.indexOf(mj),1)
        // this._mjsData.concat(this._lastMoPai)
        // this._mjsData.sort(function(a,b){return a-b})
        this.refresHoldsPos(this._mjsData)
       // MjEffect.moveHitToPos(selfHols, this._mjsData, mj,this._lastMoPai, this.refresHoldsPos.bind(this) )

        GameDataManager.room.getSelfPlayer().canPai = false
    }

    //整理出牌区
    private refresFolds(uid: number, mj: number): void {
        //拿到出牌玩家的节点
       

        let p = GameDataManager.room.getPlayerByid(uid)
        let local = GameDataManager.room.getLocalPost(p.deskPos)

        if (uid != GameDataManager.game.playerId ) {
             this._player[uid].HoldsNode.children[local == 3 ? 0 : 13].active = false
        }

        p.addFolds(mj)
        let folds = this._player[uid].FoldsNode

        let config = MajongsHoldsConfig.Folds[local]
        for (let i = 0; i < p.Folds.length; i++) {
            let SpriteIdx = 0
            if (local == 0 || local == 3) {
                SpriteIdx = folds.childrenCount - 1 - i
            } else {
                SpriteIdx = i
            }
            let sp = folds.children[SpriteIdx].children[0].getComponent(cc.Sprite)
            ResouceManager.LoadSpriteFrame(MajongsConfig.Atlas + config.cardPath + HelpTools.TileFromID(p.Folds[i]), sp, Fun(() => {
                folds.children[SpriteIdx].active = true
            }, this))
        }
    }

    //收到补花消息
    private onBuHua(data:any) : void{
        //{"id":"qpmj","action":"onBuHua","data":{"acId":876980,"hua":3,"mjids":[34]}}
        if(data.acId == GameDataManager.room.getSelfPlayer().acId){
            setTimeout(()=>{
                let mj = data.mjids[0]
                this._mjsData[this._mjsData.indexOf(data.huat)] = mj
                this.refresHoldsPos(this._mjsData)
            },1000)
        }
    }

    private onMoPai(data: { acId: number, mjids: number[] }): void {
        let p = GameDataManager.room.getPlayerByid(data.acId)
        let local = GameDataManager.room.getLocalPost(p.deskPos)

        if (data.acId != GameDataManager.game.playerId) {
            if (local == 3)
                this._player[data.acId].HoldsNode.children[0].active = true
            else
                this._player[data.acId].HoldsNode.children[13].active = true
        } else {
            //自己收到麻将
            let mj = data.mjids[0]
            this._mjsData.push(mj)
            // this._lastMoPai = mj
            GameDataManager.room.getSelfPlayer().canPai = true
            let config = MajongsHoldsConfig.Holds[0]
            let sp = this._player[data.acId].HoldsNode.children[13].children[0].getComponent(cc.Sprite)
            this._player[data.acId].HoldsNode.children[13].tag = mj
            ResouceManager.LoadSpriteFrame(MajongsConfig.Atlas + config.cardPath + HelpTools.TileFromID(mj), sp, Fun(() => {
                this._player[data.acId].HoldsNode.children[13].active = true
            }, this))
            this._player[data.acId].HoldsNode.children[13].active = true
        }

    }

    //玩家操作类型处理
    private opTypeHandler(data: any): void {
        if (data.optype == MajongOpType.chupai) {
            this.refresFolds(data.uid[0], data.mjs[0])
            if(data.uid[0] == GameDataManager.room.getSelfPlayer().acId){
                GameDataManager.room.getSelfPlayer().canPai = false
                this._mjsData.splice(this._mjsData.indexOf(data.mjs[0]),1)
                this.refresHoldsPos(this._mjsData)
            }   
        }
    }

    // 显示 Config 在界面上
    private showConfig(): void { }

    //给扑克牌添加点击事件
    private onClickCardEvent(): void {
        let cardNode = this._player[GameDataManager.game.playerId].HoldsNode
        for (let i = 0; i < cardNode.childrenCount; i++) {
            cardNode.children[i].on(cc.Node.EventType.TOUCH_START, this.outCard, this)
        }
    }

    //自己的牌的点击事件
    private outCard(evt: cc.Event): void {
        let parent = evt.target.parent

        if(evt.target.Pop == true &&  GameDataManager.room.getSelfPlayer().canPai){
            new WriteCommand(WriteCmdEvent.CMD_OpChoose, MajongOpType.chupai, evt.target.tag)
        }

        if(evt.target.Pop == true){
            for (let i = 0; i < parent.childrenCount; i++) {
                parent.children[i].Pop = false
                TweenLite.to(parent.children[i], .2, { y: 0 })
            }
        }else{
            for (let i = 0; i < parent.childrenCount; i++) {
                parent.children[i].Pop = false
                TweenLite.to(parent.children[i], .2, { y: 0 })
            }
            evt.target.Pop = true
            TweenLite.to(evt.target, .2, { y: 20 })
        }

        
    }

}